from scipy.spatial.distance import cdist
try:
    from selector._base_selector import _BaseSelector
except:
    from _base_selector import _BaseSelector


class Distance(_BaseSelector):
    def __init__(self, x, y, n_selected_features):
        super(Distance, self).__init__(x, y, n_selected_features)
        self._x = x.values.T
        self._y = y.values.T.reshape(1, -1)

    def select_features(self, metric):
        distance = cdist(XA=self._x, XB=self._y, metric=metric).squeeze()
        # sorted_idx = np.argsort(distance, axis=0).squeeze()
        return super(Distance, self).sort_features(-distance)


if __name__ == '__main__':
    import numpy as np
    import pandas as pd
    # mm = ['braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming',
    #       'jaccard', 'jensenshannon', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
    #       'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule']
    mm = ['braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming',
          'jaccard', 'jensenshannon', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto',
          'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule']

    xx_file = pd.read_pickle('../../input/high_freq_all_data_2021-02-27.pkl')

    xx = xx_file.loc[pd.date_range(start='2012-01-31', end='2016-12-31', freq='M'), list(xx_file.columns.values)[:200]]
    yy = pd.read_excel('../../input/y集合.xlsx', index_col=0).loc[xx.index, 'COM']

    res = {}
    for m in mm:
        distance, dist = Distance(x=xx, y=yy, n_selected_features=10).select_features(m)
        print(m, dist)
        res[m] = pd.DataFrame(np.nan, index=list(xx_file.columns.values)[:200], columns=['value'])
        res[m]['value'] = list(distance)
        res[m].sort_values(by='value', ascending=False, inplace=True)


